package org.sith.gl.taskmanager.server.security;

import org.sith.gl.taskmanager.server.db.dao.UserEntity;
import org.sith.gl.taskmanager.server.db.service.UserService;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;


public class CustomUserDetailService implements UserDetailsService{
     private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException, DataAccessException {

        UserEntity userEntity = userService.findByLogin(login);
        if (userEntity != null) {
            Collection<GrantedAuthority> authorites = new ArrayList<GrantedAuthority>();
            authorites.add(new GrantedAuthorityImpl("IS_AUTHENTICATED_FULLY"));
            return new User(login, "", true, true, true, true, authorites);
        } else {
            throw new BadCredentialsException("User "+ login+" not found");
        }

    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}